package com.ourygo.fileselect

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.Menu
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.Toolbar
import androidx.documentfile.provider.DocumentFile
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemLongClickListener
import com.feihua.dialogutils.util.DialogUtils
import com.ourygo.fileselect.activity.AboutActivity
import com.ourygo.fileselect.adapter.FileListAdapter
import com.ourygo.fileselect.adapter.FileSelectListRecyclerViewAdapter
import com.ourygo.fileselect.base.BaseActivity
import com.ourygo.fileselect.bean.BookMark
import com.ourygo.fileselect.bean.Files
import com.ourygo.fileselect.databinding.MainBinding
import com.ourygo.fileselect.util.FilePermissionUtil
import com.ourygo.fileselect.util.FileSelectUtil
import com.ourygo.fileselect.util.HandlerUtil
import com.ourygo.fileselect.util.ListSort
import com.ourygo.fileselect.util.SharedPreferencesUtil
import com.ourygo.fileselect.util.Utils
import com.yuyh.library.imgsel.utils.FileUtils
import java.io.File

class MainActivity : BaseActivity(), OnRefreshListener {
    private lateinit var dialogUtils: DialogUtils

    private var currentPath: String? = null
    private lateinit var flAdp: FileListAdapter
    private lateinit var fileSelectAdp: FileSelectListRecyclerViewAdapter

    private lateinit var typeArray: IntArray
    private var fileSuffix: String? = null
    private var selectName: String? = null
    private var selectNum = 0

    private lateinit var viewBinding: MainBinding

    private fun removeSelect(path: String?) {
        flAdp.removeSelect(path)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewBinding = MainBinding.inflate(layoutInflater)
        setContentView(viewBinding.root)


        val intent = intent
        typeArray =
            intent.getIntArrayExtra(FileSelectUtil.ARG_TYPE_ARRAY) ?: IntArray(Files.FILE_TYPE_FILE)
        fileSuffix = intent.getStringExtra(FileSelectUtil.ARG_FILE_SUFFIX)
        selectName = intent.getStringExtra(FileSelectUtil.ARG_SELECT_NAME)
        currentPath = intent.getStringExtra(FileSelectUtil.ARG_CURRENT_PATH)
        selectNum = intent.getIntExtra(FileSelectUtil.ARG_FILE_NUM, 1)


        initView()
        initType()
        setFileList(currentPath)
    }

    private fun initType() {
        if (typeArray.size == 1) {
            when (typeArray[0]) {
                Files.FILE_TYPE_PATH -> {
                    viewBinding.btOk.visibility = View.VISIBLE
                    setSelectName("路径选择")
                }

                Files.FILE_TYPE_FILE -> {
                    viewBinding.btOk.visibility = View.GONE
                    setSelectName("文件选择")
                }

                Files.FILE_TYPE_CDB -> {
                    viewBinding.btOk.visibility = View.GONE
                    setSelectName("Cdb选择")
                }

                Files.FILE_TYPE_CONF -> {
                    viewBinding.btOk.visibility = View.GONE
                    setSelectName("卡表选择")
                }

                Files.FILE_TYPE_CARD_PIC -> {
                    viewBinding.btOk.visibility = View.GONE
                    setSelectName("卡图压缩包选择")
                }

                Files.FILE_TYPE_LUA -> {
                    viewBinding.btOk.visibility = View.GONE
                    setSelectName("脚本选择")
                }

                Files.FILE_TYPE_ENDING -> {
                    viewBinding.btOk.visibility = View.GONE
                    setSelectName("残局存档选择")
                }

                Files.FILE_TYPE_ZIP -> {
                    viewBinding.btOk.visibility = View.GONE
                    setSelectName("ZIP选择")
                }

                Files.FILE_TYPE_PIC -> {
                    viewBinding.btOk.visibility = View.GONE
                    setSelectName("图片选择")
                }

                Files.FILE_TYPE_TXT -> {
                    viewBinding.btOk.visibility = View.GONE
                    setSelectName("文本选择")
                }

                Files.FILE_TYPE_YDK -> {
                    viewBinding.btOk.visibility = View.GONE
                    setSelectName("卡组选择")
                }

                Files.FILE_TYPE_YSE_SET -> {
                    viewBinding.btOk.visibility = View.GONE
                    setSelectName("卡图存档选择")
                }

                else -> {
                    viewBinding.btOk.visibility = View.GONE
                    if (selectName == null) {
                        setSelectName("文件选择")
                    } else {
                        setSelectName(selectName!!)
                    }
                }
            }
        } else {
            viewBinding.btOk.visibility = View.GONE
            if (selectName == null) {
                setSelectName("文件选择")
            } else {
                setSelectName(selectName!!)
            }
        }
        if (typeArray[0] != Files.FILE_TYPE_PATH && selectNum > 1) {
            viewBinding.btOk.visibility = View.VISIBLE
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK) return
        when (requestCode) {
            FilePermissionUtil.REQUEST_CODE_FOR_DIR -> if (FilePermissionUtil.isGetPermissionOk(
                    this, data
                )
            ) setFileList(currentPath)

        }
    }

    override fun onRefresh() {
        if (!FilePermissionUtil.isDataPermissionAndRequest(
                this, currentPath,
                FilePermissionUtil.REQUEST_CODE_FOR_DIR
            )
        ) {
            viewBinding.srlUpdate.isRefreshing = false
            viewBinding.srlUpdate.isEnabled = false
            return
        }
        setShowPath(currentPath)

        val file = File(currentPath)
        var listFile: Array<File>? = null
        var documentFile: Array<DocumentFile>? = null
        if (!FilePermissionUtil.isCheckFilePermission(currentPath)) {
            listFile = file.listFiles()
            if (listFile == null) {
                currentPath = file.parentFile.absolutePath
                val intent = Intent()
                intent.putExtra(FileSelectUtil.ARG_PATH, "")
                setResult(RESULT_CANCELED, intent)
                super.onBackPressed()
                return
            }
        } else {
            documentFile = FilePermissionUtil.getDocumentFile(this, currentPath).listFiles()
            if (documentFile == null) {
                currentPath = file.parentFile.absolutePath
                val intent = Intent()
                intent.putExtra(FileSelectUtil.ARG_PATH, "")
                setResult(RESULT_CANCELED, intent)
                super.onBackPressed()
                return
            }
        }
        val data: MutableList<Files> = ArrayList()
        if (listFile != null) {
            Log.e("MainAcitivty", "刷新 " + (listFile.size > 100))
            if (listFile.size > 100) {
                viewBinding.srlUpdate.isRefreshing = true
                val finalListFile: Array<File> = listFile
                Thread {
                    loadFiles(data, finalListFile)
                    HandlerUtil.sendMessage(handler, FILE_LOAD_OK, data)
                }.start()
            } else {
                loadFiles(data, listFile)
                HandlerUtil.sendMessage(handler, FILE_LOAD_OK, data)
            }
        } else {
            val finalDocumentFile = documentFile
            Thread {
                for (f: DocumentFile in finalDocumentFile!!) {
                    if (f.name != null && !f.name!!.startsWith(".")) {
                        val fs = Files(f)
                        val name: String? = f.name
                        if (f.isDirectory) {
                            //如果是文件夹
                            fs.type = (Files.FILE_TYPE_PATH)
                            data.add(fs)
                        } else {
                            if (name!!.endsWith(".cdb")) {
                                fs.type = (Files.FILE_TYPE_CDB)
                            } else if (name.endsWith(".conf")) {
                                fs.type = Files.FILE_TYPE_CONF
                            } else if (name.endsWith("pics.zip")) {
                                fs.type = Files.FILE_TYPE_CARD_PIC
                            } else if (name.endsWith(".lua")) {
                                fs.type = (Files.FILE_TYPE_LUA)
                            } else if (name.endsWith(".cjcd")) {
                                fs.type = (Files.FILE_TYPE_ENDING)
                            } else if (name.endsWith(".zip")) {
                                fs.type = (Files.FILE_TYPE_ZIP)
                            } else if (name.endsWith(".jpg") || name.endsWith(".bpm") || name.endsWith(
                                    ".jpeg"
                                ) || name.endsWith(".png")
                            ) {
                                fs.type = (Files.FILE_TYPE_PIC)
                            } else if (name.endsWith(".txt")) {
                                fs.type = (Files.FILE_TYPE_TXT)
                            } else if (name.endsWith(".yse-set")) {
                                fs.type = (Files.FILE_TYPE_YSE_SET)
                            } else if (fileSuffix != null && name.endsWith(fileSuffix!!)) {
                                fs.type = (Files.FILE_TYPE_CUSTOM)
                            } else {
                                fs.type = (Files.FILE_TYPE_FILE)
                            }
                            for (type: Int in typeArray) {
                                if (type == fs.type) {
                                    data.add(fs)
                                    break
                                }
                            }
                        }
                    }
                }
                ListSort.listSort(data)
                HandlerUtil.sendMessage(handler, FILE_LOAD_OK, data)
            }.start()
        }
    }

    private fun loadFiles(filesList: MutableList<Files>, files: Array<File>) {
        for (f: File in files) {
            if (!f.name.startsWith(".")) {
                val fs = Files(f)
                val name = f.name
                if (f.isDirectory) {
                    //如果是文件夹
                    fs.type = Files.FILE_TYPE_PATH
                    filesList.add(fs)
                } else {
                    if (name.endsWith(".cdb")) {
                        fs.type = Files.FILE_TYPE_CDB
                    } else if (name.endsWith(".conf")) {
                        fs.type = Files.FILE_TYPE_CONF
                    } else if (name.endsWith("pics.zip")) {
                        fs.type = Files.FILE_TYPE_CARD_PIC
                    } else if (name.endsWith(".lua")) {
                        fs.type = Files.FILE_TYPE_LUA
                    } else if (name.endsWith(".cjcd")) {
                        fs.type = Files.FILE_TYPE_ENDING
                    } else if (name.endsWith(".zip")) {
                        fs.type = Files.FILE_TYPE_ZIP
                    } else if (name.endsWith(".jpg") || name.endsWith(".bpm") || name.endsWith(
                            ".jpeg"
                        ) || name.endsWith(".png")
                    ) {
                        fs.type = Files.FILE_TYPE_PIC
                    } else if (name.endsWith(".txt")) {
                        fs.type = Files.FILE_TYPE_TXT
                    } else if (name.endsWith(".yse-set")) {
                        fs.type = Files.FILE_TYPE_YSE_SET
                    } else if (fileSuffix != null && name.endsWith(fileSuffix!!)) {
                        fs.type = Files.FILE_TYPE_CUSTOM
                    } else {
                        fs.type = Files.FILE_TYPE_FILE
                    }
                    for (type: Int in typeArray) {
                        if (type == fs.type) {
                            filesList.add(fs)
                            break
                        }
                    }
                }
            }
        }
        ListSort.listSort(filesList)
    }


    @SuppressLint("HandlerLeak")
    var handler: Handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                FILE_LOAD_OK -> {
                    Log.e("MainActivity", "加载完毕")
                    val files = msg.obj as MutableList<Files>
                    flAdp.setNewInstance(files)
                    viewBinding.srlUpdate.isRefreshing = false
                    viewBinding.srlUpdate.isEnabled = true
                }
            }
        }
    }

    fun setFileList(path: String?) {
        currentPath = path
        if (FilePermissionUtil.isCheckFilePermission(path)) viewBinding.srlUpdate.isRefreshing =
            true
        onRefresh()
        // TODO: Implement this method
    }

    private fun setShowPath(path: String?) {
        var path = path
        val length = path!!.length
        if (length > 20) {
            path = path.substring(length - 20, length)
        }
        viewBinding.toolbar.toolbar.subtitle = path
    }

    private fun setSelectName(name: String) {
        viewBinding.toolbar.toolbar.title = name
    }

    private fun initView() {
        dialogUtils = DialogUtils.getInstance(this)

        viewBinding.srlUpdate.setColorSchemeColors(Utils.c(this, R.color.colorAccent))
        viewBinding.srlUpdate.setOnRefreshListener(this)
        viewBinding.srlUpdate.setEnabled(false)

        if (selectNum > 1) {
            //viewBinding.llSelectList.setVisibility(View.VISIBLE);
            fileSelectAdp = FileSelectListRecyclerViewAdapter(
                this@MainActivity,
                ArrayList()
            )

            fileSelectAdp.setOnItemLongClickListener { adapter: BaseQuickAdapter<*, *>, _: View?, position: Int ->
                val filePath: String =
                    (adapter.getItem(position) as File).getParent() ?: Utils.PATH_GEN
                if (filePath != currentPath) setFileList(filePath)
                true
            }
            fileSelectAdp.setOnItemClickListener { adapter: BaseQuickAdapter<*, *>, _: View?, position: Int ->
                if (isLoadingFile) return@setOnItemClickListener
                val item: Files = adapter.getItem(position) as Files
                val views: Array<View> =
                    dialogUtils.dialogt(item.name, "文件路径：" + item.absolutePath)
                val b1: Button = views[0] as Button
                val b2: Button = views[1] as Button
                b1.text = s(R.string.close)
                b2.text = s(R.string.cancel_select)
                b2.setTextColor(Utils.c(this, R.color.red))
                b1.setOnClickListener { dialogUtils.dis() }
                b2.setOnClickListener {
                    fileSelectAdp.remove(item)
                    removeSelect(item.absolutePath)
                }
            }
            val llm = LinearLayoutManager(this)
            llm.orientation = LinearLayoutManager.HORIZONTAL
            viewBinding.rvSelectList.setLayoutManager(llm)
            viewBinding.rvSelectList.setAdapter(fileSelectAdp)
        } /*else{
			viewBinding.llSelectList.setVisibility(View.GONE);
		}*/

        flAdp = FileListAdapter(this, ArrayList(), selectNum > 1)
        val newFileLayout = LayoutInflater.from(this).inflate(R.layout.header_file_list, null)
        newFileLayout.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View) {
                if (isLoadingFile) return
                val vs = dialogUtils.dialoge("", "请输入文件夹名称")
                val et = vs[0] as EditText
                vs[1].setOnClickListener {
                    val name = et.text.toString().trim { it <= ' ' }
                    if (TextUtils.isEmpty(name)) {
                        Utils.show(this@MainActivity, "文件名名称不能为空")
                    } else {
                        if (TextUtils.isEmpty(
                                FileUtils.createDir(
                                    File(
                                        currentPath,
                                        name
                                    ).absolutePath
                                )
                            )
                        ) {
                            Utils.show(this@MainActivity, "文件夹创建失败")
                        } else {
                            dialogUtils.dis()
                            Utils.show(this@MainActivity, "创建成功")
                            setFileList(currentPath)
                        }
                    }
                }
            }
        })
        flAdp.setHeaderView(newFileLayout)
        if (currentPath == null) {
            currentPath = Utils.PATH_GEN
        }
        viewBinding.rvFileList.setLayoutManager(LinearLayoutManager(this))
        viewBinding.rvFileList.setAdapter(flAdp)
        Utils.initToolbar(this, viewBinding.toolbar.toolbar, "", true)
        viewBinding.toolbar.toolbar.setNavigationIcon(androidx.appcompat.R.drawable.abc_ic_clear_material)
        viewBinding.toolbar.toolbar.setOnMenuItemClickListener(onMenuItemClick)
        viewBinding.toolbar.toolbar.setNavigationOnClickListener {
            val intent = Intent()
            intent.putExtra(FileSelectUtil.ARG_PATH, "")
            setResult(RESULT_CANCELED, intent)
            finish()
            // TODO: Implement this method
        }
        viewBinding.toolbar.toolbar.setSubtitleTextAppearance(this, R.style.ToolbarSubtitleTheme)
        flAdp.setOnItemClickListener { _: BaseQuickAdapter<*, *>?, _: View?, position: Int ->
            if (isLoadingFile) return@setOnItemClickListener
            val files: Files = flAdp.data[position]
            if (files.isDirectory) {
                setFileList(files.absolutePath)
            } else {
                if (typeArray[0] != Files.FILE_TYPE_PATH) {
                    //如果是选择文件
                    if (selectNum > 1) {
                        //如果是多选
                        val li: MutableList<String> = flAdp.selectList
                        for (i in li.indices) {
                            if ((li[i] == files.absolutePath)) {
                                li.removeAt(i)

                                fileSelectAdp.remove(files)
                                if (fileSelectAdp.getItemCount() == 0) {
                                    viewBinding.llSelectList.visibility = View.GONE
                                }
                                flAdp.notifyItemChanged(position + flAdp.headerLayoutCount)
                                return@setOnItemClickListener
                            }
                        }
                        if (li.size == selectNum) {
                            Utils.show(this@MainActivity, "最多只能选择" + selectNum + "个文件")
                            return@setOnItemClickListener
                        }
                        li.add(files.absolutePath)
                        if (viewBinding.llSelectList.visibility == View.GONE) {
                            viewBinding.llSelectList.visibility = View.VISIBLE
                        }
                        fileSelectAdp.addData(files)
                        flAdp.notifyItemChanged(position + flAdp.headerLayoutCount)
                    } else {
                        //如果是选择路径
                        val intent = Intent()
                        intent.putExtra(FileSelectUtil.ARG_PATH, files.absolutePath)
                        intent.putExtra(
                            FileSelectUtil.ARG_FILE_TYPE,
                            flAdp.data[position].type
                        )
                        setResult(RESULT_OK, intent)
                        finish()
                    }
                } else {
                    Toast.makeText(
                        this@MainActivity,
                        "请在想选择的路径下点确定",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        }

        flAdp.setOnItemLongClickListener(object : OnItemLongClickListener {
            override fun onItemLongClick(
                adapter: BaseQuickAdapter<*, *>,
                view: View,
                position: Int
            ): Boolean {
                if (!flAdp.data[position].file.isDirectory()) {
                    return false
                }


                val files: Files = adapter.getItem(position) as Files

                val et = EditText(this@MainActivity)
                et.setHint("请输入标签名")
                val dialog: AlertDialog = AlertDialog.Builder(
                    this@MainActivity
                )
                    .setIcon(R.drawable.ic_launcher)
                    .setTitle("添加路径书签")
                    .setView(et)
                    .setNegativeButton("添加", null)
                    .setPositiveButton(
                        "取消"
                    ) { _, _ ->
                    }.show()
                dialog.getButton(AlertDialog.BUTTON_NEGATIVE)
                    .setOnClickListener(object : View.OnClickListener {
                        override fun onClick(v: View) {
                            val name: String = et.getText().toString().trim()
                            if (TextUtils.isEmpty(name)) {
                                Utils.show(this@MainActivity, "标签名不能为空")
                                return
                            }
                            val bm: BookMark = BookMark.toBookMark(
                                name,
                                files.file.path,
                                R.drawable.listfile_folder
                            )

                            if (SharedPreferencesUtil.addBookMark(this@MainActivity, bm)) {
                                Utils.show(this@MainActivity, "添加成功")
                                dialog.dismiss()
                            } else {
                                Utils.show(this@MainActivity, "该书签名已存在")
                            }
                        }
                    })
                handler.postDelayed({ Utils.ShowKeyboard(et) }, 100)
                return true
            }
        })
        viewBinding.btBackspace.setOnClickListener(object : View.OnClickListener {
            override fun onClick(p1: View) {
                if (isLoadingFile) return
                if (!backLastFile()) {
                    Toast.makeText(this@MainActivity, "没有上一级了喵~", Toast.LENGTH_SHORT).show()
                }
                // TODO: Implement this method
            }
        })
        viewBinding.btOk.setOnClickListener {
            if (isLoadingFile) return@setOnClickListener
            val intent = Intent()
            if (typeArray[0] != Files.FILE_TYPE_PATH) {
                val ls: ArrayList<String> = flAdp.selectList
                if (ls.size == 0) {
                    Utils.show(this@MainActivity, "未选择文件")
                } else {
                    intent.putExtra(FileSelectUtil.ARG_PATH_LIST, ls)
                    setResult(RESULT_OK, intent)
                }
            } else {
                intent.putExtra(FileSelectUtil.ARG_PATH, currentPath)
                intent.putExtra(FileSelectUtil.ARG_FILE_TYPE, Files.FILE_TYPE_PATH)
                setResult(RESULT_OK, intent)
            }
            finish()
        }


        // TODO: Implement this method
    }

    private val isLoadingFile: Boolean
        /**
         * 是否正在加载文件
         * @return
         */
        get() {
            if (viewBinding.srlUpdate.isRefreshing) {
                Utils.show("文件加载中，请等待加载完毕后再操作")
                return true
            }
            return false
        }

    private fun backLastFile(): Boolean {
        val f = Files(this, currentPath)
        if (f.isDirectory) {
            val path = f.parentPath
            if (path != null) {
                Log.e("MainActivity", "上一级目录$path")
                setFileList(path)
                return true
            }
        }
        return false
        // TODO: Implement this method
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        //getMenuInflater().inflate(R.menu.menu_qd, menu);
        menuInflater.inflate(R.menu.main_menu, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onBackPressed() {
        if (isLoadingFile) return
        if (!backLastFile()) {
            val intent = Intent()
            intent.putExtra(FileSelectUtil.ARG_PATH, "")
            setResult(RESULT_CANCELED, intent)
            super.onBackPressed()
        }
    }

    private val onMenuItemClick: Toolbar.OnMenuItemClickListener =
        Toolbar.OnMenuItemClickListener { p1 ->
            when (p1.itemId) {
                R.id.main_about -> startActivity(
                    Intent(
                        this@MainActivity,
                        AboutActivity::class.java
                    )
                )
            }
            true
        }

    companion object {
        private const val FILE_LOAD_OK = 0
    }
}
